package org.example.learn.javassist;

import javassist.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestA {

    public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        // 对象容器
        ClassPool pool = ClassPool.getDefault();

        // 创建类：类路径和名称
        CtClass ctClass = pool.makeClass("org.example.learn.javassist.HelloWorld");

        // 添加方法
        CtMethod method = new CtMethod(CtClass.voidType,"main",new CtClass[]{pool.get(String[].class.getName())},ctClass);
        method.setModifiers(Modifier.PUBLIC + Modifier.STATIC);
        method.setBody("{System.out.println(\"javassist hello world\");}");
        ctClass.addMethod(method);

        // 创建无参构造方法
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{},ctClass);
        ctConstructor.setBody("{}");
        ctClass.addConstructor(ctConstructor);

        // 输出类内容
        ctClass.writeFile();

        // 调用
        Class<?> clazz = ctClass.toClass();
        Object val = clazz.newInstance();

        Method main = clazz.getDeclaredMethod("main",String[].class);
        main.invoke(val,(Object) new String[1]);
    }
}
